package com.gitee.vueantd.common.utils.download;

import lombok.extern.log4j.Log4j2;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@Log4j2
public class HttpFileDownloadUtil {
  private HttpFilesReader httpFilesReader = null;

  private void createHttpFileReader() {
    httpFilesReader = new HttpLocalFilesReader();
  }

  public void openFile(String fileName) throws Exception {
    List<HttpFileInfo> httpFileInfoList = new ArrayList();
    httpFileInfoList.add(new HttpFileInfo(0, fileName));
    createHttpFileReader();
    httpFilesReader.setFileList(httpFileInfoList);
  }

  public void openFileList(List<String> fileNameList) throws Exception {
    List<HttpFileInfo> httpFileInfoList = new ArrayList();
    for (String fileName : fileNameList) {
      httpFileInfoList.add(new HttpFileInfo(0, fileName));
    }
    createHttpFileReader();
    httpFilesReader.setFileList(httpFileInfoList);
  }

  public void openFileInfoList(List<HttpFileInfo> httpFileInfoList) throws Exception {
    createHttpFileReader();
    httpFilesReader.setFileList(httpFileInfoList);
  }

  public long getLength() throws Exception {
    return httpFilesReader.getTotalFileSize();
  }

  public long readContent(OutputStream output, long startPos, long endPos, BandWidthLimiter limiter) throws Exception {
    long totalFileSize = getLength();
    if (totalFileSize == 0) {
      return 0;
    }
    long readed = 0;
    if (startPos < endPos) {
      long len = endPos - startPos + 1;
      readed = httpFilesReader.readBuffer(startPos, len, output, limiter);
      if (readed != len) {
        log.info("something wrong in prcoess read buffer");
      }
    }
    log.debug("readed:" + readed);
    return readed;
  }
}
